package cn.tedu.bonfire.front.account.service.impl;

import cn.tedu.bonfire.common.cache.IUserCacheRepository;
import cn.tedu.bonfire.common.enumerator.ServiceCode;
import cn.tedu.bonfire.common.ex.ServiceException;
import cn.tedu.bonfire.common.pojo.po.PhoneCaptchaCachePO;
import cn.tedu.bonfire.common.util.SMS;
import cn.tedu.bonfire.front.account.dao.persist.repository.IUserRegisterRepository;
import cn.tedu.bonfire.front.account.dao.persist.repository.IUserRepository;
import cn.tedu.bonfire.front.account.pojo.entity.User;
import cn.tedu.bonfire.front.account.pojo.entity.UserRole;
import cn.tedu.bonfire.front.account.pojo.param.UserRegisterParam;
import cn.tedu.bonfire.front.account.service.IUserRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Random;

@Slf4j
@Repository
public class UserRegisterServiceImpl implements IUserRegisterService {

    @Autowired
    IUserRepository userRepository;

    @Autowired
    IUserRegisterRepository userRegisterRepository;

    @Autowired
    IUserCacheRepository userCacheRepository;

    @Override
    public void register(UserRegisterParam userRegisterParam) {
        String phone = userRegisterParam.getPhone();
        Long count = 0L;
        //检查手机号是否被占用
        count = userRepository.countByPhone(phone);
        if (count > 0) {
            String message = "添加用户失败，手机号已经被占用！";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        // 检查手机验证码是否正确
        String captcha = userRegisterParam.getCaptcha();
        PhoneCaptchaCachePO cacheCaptcha = userCacheRepository.getPhoneCaptcha(phone);
        if (cacheCaptcha == null) {
            String message = "请先获取验证码!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CAPTCHA, message);
        }
        if (!cacheCaptcha.getCaptcha().equals(captcha)) {
            String message = "验证码错误!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CAPTCHA, message);
        }

        User user = new User();

        BeanUtils.copyProperties(userRegisterParam, user);
        user.setDescription("普通用户");
        user.setEnable(ENABLE_STATE_ON);
        user.setUsername(phone);
        // 默认头像
        user.setAvatar("https://img2.huashi6.com/images/resource/thumbnail/2022/03/31/71132_89210698475.jpg?imageMogr2/quality/100/interlace/1/thumbnail/2000x%3E");

        // 默认昵称
        String nickname;
        do {
            nickname = CreateNicknameRandom();
            count = userRepository.countByNickname(nickname);
        } while (count < 0);
        user.setNickname(nickname);

        int rows = userRegisterRepository.insert(user);
        if (rows != 1) {
            String message = "注册失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        // 插入角色联系表
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(3L);
        rows = userRegisterRepository.insertUserRole(userRole);

        if (rows != 1) {
            String message = "注册失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
    }

    @Override
    public void getCaptchaByPhone(String phone) {
        userCacheRepository.deletePhoneCaptcha(phone);
        PhoneCaptchaCachePO phoneCaptchaCachePO = SMS.send(phone);
        userCacheRepository.savePhoneCaptcha(phone, phoneCaptchaCachePO);
    }


    // 生成默认昵称
    private String CreateNicknameRandom() {
        String nickname = "用户";
        Random random = new Random();
        for (int i = 0; i < 8; i++) {
            int t = random.nextInt(3) + 1;
            switch (t) {
                case 1:
                    int num = random.nextInt(10);
                    nickname += num;
                    break;
                case 2:
                    int k = random.nextInt(26) + 97;
                    char k1 = (char) k;
                    nickname += k1;
                    break;
                case 3:
                    int k2 = random.nextInt(26) + 65;
                    char k3 = (char) k2;
                    nickname += k3;
                    break;
            }
        }
        return nickname;
    }
}
